<template>
    <div class="watermark" ref="watermark">
        <slot></slot>
    </div>
</template>
<script>
import { defineComponent } from '@vue/composition-api'

export default defineComponent({
    setup() {
        
    },
    data(){
        return{
            
        }
    },
    props:{
        wText:{
            type:String,
            default:"watermark"
        }
    },
    created () {
        
    },
    mounted () {
        this.loadMark();
    },
    methods:{
        loadMark(){
            let self = this;
            let parentNode = self.$refs["watermark"];
            let {base64,size} = self.createWaterMark("赵帅峰123");
            let ob = null;
            const div = document.createElement("div");
            div.style.backgroundImage = `url(${base64})`;
            div.style.backgroundSize = `${size}px,${size}px`;
            div.style.backgroundRepeat = "repeat";
            div.style.position = "absolute"
            div.style.zIndex = '1';
            div.style.inset = 0;
            div.id = "watermark";
            ob = new MutationObserver((recodrs)=>{
                if(recodrs[0].type == "childList"){
                    for (const key of recodrs[0].removedNodes) {
                        if(key.id == 'watermark'){
                            // alert("水印被删除")
                            ob.disconnect()   //解除监听绑定
                            ob = null;
                            self.loadMark(parentNode)
                        }
                    }
                }
            })
            ob.observe(parentNode,{
                childList : true,   //监听元素的内容是否有变化
                attributes : true,  //监听元素的属性有没有变化
                subtree : true      //监听元素的字树有没有变化
            })
            parentNode.appendChild(div);
        },
        createWaterMark(){
            let self = this;
            const canvas = document.createElement("canvas");
            const Pixel = window.devicePixelRatio || 1;
            const fontsize = 18 * Pixel;
            const ctx = canvas.getContext("2d");
            const { width } = ctx.measureText(self.wText);
            const canvasWidth = Math.max(200,width) * Pixel;
            canvas.width = canvasWidth;
            canvas.height = canvasWidth;
            ctx.translate(canvasWidth / 2 , canvasWidth / 2);
            ctx.rotate(45);
            ctx.font = `${fontsize}px 宋体`;
            ctx.fillStyle = "rgba(0,0,0,0.3)";
            ctx.textAlign = "center";
            ctx.textBaseline = "middle";
            ctx.fillText(self.wText,0,0)
            return{
                base64:canvas.toDataURL(),
                size:canvasWidth
            }
        }
    }
})
</script>
<style scoped>
    .watermark{
        width: 100%;
        height: 100%;
    }
</style>